package com.tmc.service.intcar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.intcar.EthPushDriverReq;
import com.tmc.constant.IntcarOrderConstant;
import com.tmc.entity.intcar.IntcarDriver;
import com.tmc.entity.intcar.IntcarOrder;
import com.tmc.util.ObjectUtil;

/**
 * @author zhang
 * @date 2017年12月29日 下午4:28:05 
 */
@Service
public class IntcarPushDriverServiceImpl {
	
	private Log log = LogFactory.getLog(IntcarPushDriverServiceImpl.class);
	
	@Autowired
	private IntcarOrderServiceImpl orderService;
	
	public CommonResult pushDriver(ContextInfo context, EthPushDriverReq request){
		CommonResult check = this.check(request);
		if(!check.isSuccess()){
			return check;
		}
		
		IntcarOrder dbOrder = orderService.getById(context, request.getOrderID());
		if(dbOrder == null){
			return CommonResult.makeFail("ID为"+request.getOrderID()+"的订单不存在！");
		}
		if(!dbOrder.getVendorOrderID().equals(request.getVendorOrderID())){
			return CommonResult.makeFail("供应商ID错误！");
		}
		//VendorService service = ServiceCenter.getService(dbOrder.getVendor());
		try {
			if(request.getConfirmType() == IntcarOrderConstant.DRIVER_CONFIRMTYPE_ACCEPTED){
				dbOrder.setOrderStatus(IntcarOrderConstant.ORDER_STATUS_PENDEDCAR);
			}else{
				dbOrder.setOrderStatus(IntcarOrderConstant.ORDER_STATUS_REFORMABLECAR);
			}
			// 更新本地司导信息
			IntcarDriver driver = buildDriver(request);
			dbOrder.setDriver(driver);
			CommonResult result = orderService.pushDriver(context, dbOrder);
			return result;
		} catch (Exception e) {
			log.error("司导指派出错！", e);
		}
		return CommonResult.makeFail("司导指派出错！");
	}
	
	private IntcarDriver buildDriver(EthPushDriverReq request){
		IntcarDriver bean = ObjectUtil.makeTargetBean(request.getDriver(), IntcarDriver.class);
		bean.setOrderID(request.getOrderID());
		return bean;
	}
	
	private CommonResult check(EthPushDriverReq request){
		if(request.getOrderID() == null){
			CommonResult.makeFail("订单ID不能为空！"); 
		}
		if(request.getConfirmType() == null){
			CommonResult.makeFail("确认类型不能为空！"); 
		}
		if(request.getDriver() == null){
			CommonResult.makeFail("司导不能为空！");
		}
		if(ObjectUtil.noText(request.getDriver().getDriverName())){
			return CommonResult.makeFail("司导姓名不能为空！");
		}
		if(ObjectUtil.noText(request.getDriver().getDriverPhone())){
			return CommonResult.makeFail("司导电话不能为空！");
		}
		return CommonResult.makeSuccess();
	}
}
